<template>
    <div style="margin: 20px 10px; height: 500px;">
        <a-row>
            <a-col :span="3">
                <div style="background-color: white; height: 500px">
                    <div class="chooseByAreaBox">
                        <span class="chooseByArea">按区域筛选</span>
                    </div>

                    <div class="area-list">
                        <a-tree
                            v-if="provinces.length > 0"
                            :selected-keys="selectedKeys"
                            :tree-data="provinces"
                            default-expand-all
                            @select="onSelect">
                            <template #title="{ title, key }">
                                <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                                <template v-else>{{ title }}</template>
                            </template>
                        </a-tree>
                    </div>
                </div>
            </a-col>

            <a-col offset="1" span="20" style="background-color: white;">
                <a-row style="margin-top: 6px">
                    <a-col offset="1" span="5">
                        <span>机器状态:</span>

                        <a-dropdown allow-clear>
                            <a-menu slot="overlay" :selectedKeys="machineStatus" @click="handleMenuClick">
                                <a-menu-item key="0">静止</a-menu-item>
                                <a-menu-item key="1">工作</a-menu-item>
                                <a-menu-item key="2">离线</a-menu-item>
                                <a-menu-item key="3">强拆</a-menu-item>
                                <a-menu-item key="4">全部</a-menu-item>
                            </a-menu>
                            <a-button style="margin-left: 8px">{{ machineStatusTips }}
                                <a-icon type="down"/>
                            </a-button>
                        </a-dropdown>
                    </a-col>

                    <a-col span="8">
                        <a-input-search v-model="keyword" allow-clear enter-button
                                        placeholder="请输入电子标签或环保标签编号"
                                        @search="onSearch"/>
                    </a-col>

                    <a-col offset="7" span="3">
                        <a-button type="primary" @click="addMachine">
                            <a-icon type="plus"></a-icon>
                            新增
                        </a-button>

                        <a-modal
                            :title="addOrUpdate ? '添加机械':'编辑机械'"
                            :visible="visible"
                            :width="900"
                            @cancel="handleCancel"
                            @ok="handleOk"
                            :maskClosable="!addOrUpdate"
                        >

                            <a-form :form="form" :label-col="{ span: 10, offset: 0}" :wrapper-col="{ span: 12 }">
                                <a-row>
                                    <a-col span="12">
                                        <a-form-item v-show="false" label="电子标签id">
                                            <a-input
                                                v-decorator="['id', { rules: [{ required: false, message: '请输入电子标签编号!' }] }]"/>
                                        </a-form-item>
                                        <a-form-item label="电子标签编号">
                                            <a-input
                                                v-decorator="['locator_mobile', { rules: [{ required: true, message: '请输入电子标签编号!' }] }]"/>
                                        </a-form-item>
                                        <a-form-item label="机械所有人">
                                            <a-input
                                                v-decorator="['contacts', { rules: [{ required: true, message: '请输入所有人!' }] }]"/>
                                        </a-form-item>
                                        <a-form-item label="机械所在区域">
                                            <a-cascader
                                                v-decorator="[
                                                              'areas',
                                                              {
                                                                rules: [
                                                                  { type: 'array', required: true, message: '请选择所属区域!' },
                                                                ],
                                                              },
                                                              ]"
                                                :field-names="{ label: 'title', value: 'key', children: 'children' }"
                                                :options="provinces"
                                                placeholder="请选择所在区域"
                                            />
                                        </a-form-item>
                                        <!--                                        <a-form-item label="电子标签状态">-->
                                        <!--                                            <a-select-->
                                        <!--                                                v-decorator="[-->
                                        <!--                                                    'mark',-->
                                        <!--                                                    { rules: [{ required: true, message: '请选择电子标签状态!' }] },-->
                                        <!--                                                    ]"-->
                                        <!--                                                placeholder="请选择">-->

                                        <!--                                                <a-select-option :value="1">-->
                                        <!--                                                    可用-->
                                        <!--                                                </a-select-option>-->
                                        <!--                                                <a-select-option :value="0">-->
                                        <!--                                                    不可用-->
                                        <!--                                                </a-select-option>-->
                                        <!--                                            </a-select>-->
                                        <!--                                        </a-form-item>-->
                                    </a-col>
                                    <a-col span="12">
                                        <a-form-item label="环保编号">
                                            <a-input
                                                v-decorator="['mec_no', { rules: [{ required: true, message: '请输入环保编号!' }] }]"/>
                                        </a-form-item>
                                        <a-form-item label="联系电话">
                                            <a-input
                                                v-decorator="['mobile', { rules: [{ required: true, message: '请输入联系电话!' },
                                                {max: 11, message: '电话号码的长度不能超过11位'}] }]"/>
                                        </a-form-item>

                                        <a-form-item label="绑定机械类型">
                                            <a-cascader
                                                v-decorator="[
                                                              'type_id',
                                                              {
                                                                rules: [
                                                                  { type: 'array', required: true, message: '请选择绑定机械类型!' },
                                                                ],
                                                              },
                                                            ]"
                                                :fieldNames="{
                                                    value: 'id',
                                                    label: 'category_name',
                                                    children: 'children'
                                                }"
                                                :options="machineTypesBeFilter"
                                                placeholder="请选择绑定机械类型"
                                            />
                                        </a-form-item>

                                        <a-form-item label="排放检测到期时间">
                                            <a-date-picker v-decorator="['check_end_time']"/>
                                        </a-form-item>
                                    </a-col>
                                </a-row>

                                <a-form-item :label-col="{ span: 4, offset: 0}" label="机械照片">
                                    <a-row>
                                        <a-col span="6">
                                            <a-upload
                                                :customRequest="uploadAppearanceImg"
                                                :file-list="appearanceList"
                                                :multiple="false"
                                                :showUploadList="true"
                                                list-type="picture-card"
                                                name="lemonFile"
                                                @change="handleApprenceChange"
                                                @preview="handlePreview"
                                            >
                                                <div v-if="appearanceList.length < 1">
                                                    <a-icon type="plus"/>
                                                    <div class="ant-upload-text">
                                                        外观
                                                    </div>
                                                </div>
                                            </a-upload>
                                        </a-col>
                                        <a-col span="6">
                                            <a-upload
                                                :customRequest="uploadMachineImg"
                                                :file-list="machineList"
                                                :showUploadList="true"
                                                list-type="picture-card"
                                                name="lemonFile"
                                                @change="handleMachineChange"
                                                @preview="handlePreview"
                                            >
                                                <div v-if="machineList.length < 1">
                                                    <a-icon type="plus"/>
                                                    <div class="ant-upload-text">
                                                        机械名牌
                                                    </div>
                                                </div>
                                            </a-upload>
                                        </a-col>
                                        <a-col span="6">
                                            <a-upload
                                                :customRequest="uploadEngineImg"
                                                :file-list="engineList"
                                                :showUploadList="true"
                                                list-type="picture-card"
                                                name="lemonFile"
                                                @change="handleEngineChange"
                                                @preview="handlePreview"
                                            >

                                                <div v-if="engineList.length < 1">
                                                    <a-icon type="plus"/>
                                                    <div class="ant-upload-text">
                                                        发动机名牌
                                                    </div>
                                                </div>

                                            </a-upload>
                                        </a-col>
                                        <a-col span="6">
                                            <a-upload
                                                :customRequest="uploadOtherImg"
                                                :file-list="otherList"
                                                :showUploadList="true"
                                                list-type="picture-card"
                                                name="lemonFile"
                                                @change="handleOtherChange"
                                                @preview="handlePreview"
                                            >
                                                <div v-if="otherList.length < 1">
                                                    <a-icon type="plus"/>
                                                    <div class="ant-upload-text">
                                                        其他
                                                    </div>
                                                </div>
                                            </a-upload>


                                        </a-col>
                                    </a-row>

                                </a-form-item>
                            </a-form>
                        </a-modal>

                        <a-modal :footer="null" :visible="previewVisible" @cancel="previewVisible=false">
                            <img :src="previewImage" alt="example" style="width: 100%"/>
                        </a-modal>

                    </a-col>
                </a-row>

                <a-table :columns="columns" :data-source="data" :pagination="false" rowKey="id">

          <span slot="status" slot-scope="item">
            <span v-if="item.status === 0" style="color: red">静止</span>
            <span v-else-if="item.status === 1" style="color: green">运动</span>
            <span v-else-if="item.status === 2" style="color: gray">离线</span>
            <span v-else-if="item.status === 3" style="color: orange">强拆</span>
          </span>

                    <span slot="freeze" slot-scope="item">
            <a-switch :checked="item.mark===1" checked-children="开" un-checked-children="关"
                      @change="changeMachineMark(item, $event)"/>
          </span>

                    <span slot="action" slot-scope="item">
                        <a-button size="small" type="primary" @click="edit(item)">编辑</a-button>

                         <a-popconfirm
                             cancel-text="No"
                             ok-text="Yes"
                             title="删除后将不能恢复，确认删除吗？"
                             @cancel="cancel"
                             @confirm="confirm(item.id)">
                            <a-button size="small" type="danger">删除</a-button>
                         </a-popconfirm>

                         <a-button v-show="item.status === 3" size="small" type="primary"
                                   @click="recover(item)">强拆恢复</a-button>

                    </span>
                </a-table>

                <a-pagination v-model="current" :default-current="2"
                              :pageSize="pageSize"
                              :pageSizeOptions="['5','10', '20', '30', '40']"
                              :showSizeChanger="true"
                              :showTotal="total => `共 ${total} 条`"
                              :total="total"
                              show-quick-jumper
                              @change="onChange" @showSizeChange="onShowSizeChange"/>

            </a-col>
        </a-row>


    </div>
</template>

<script>

import {METHOD, request} from "@/utils/request";
import Vue from "vue";
import moment from "moment";
import {RESPONSE} from "../../../utils/request";


const columns = [
    {
        title: '电子标签编号',
        key: 'locator_mobile',
        dataIndex: 'locator_mobile',
    },
    {
        title: '环保编码',
        dataIndex: 'mec_no',
        key: 'mec_no',
    },
    {
        title: '机械类型',
        key: 'type_name',
        dataIndex: 'type_name',
    },
    {
        title: '联系方式',
        key: 'mobile',
        dataIndex: 'mobile',
    },
    {
        title: '机械状态',
        key: 'mark',
        scopedSlots: {customRender: 'status'},
    },
    {
        title: '电量',
        key: 'electric',
        dataIndex: 'electric',
    },
    {
        title: '冻结电子标签',
        key: 'freeze',
        scopedSlots: {customRender: 'freeze'},
    },
    {
        title: '操作',
        key: 'action',
        scopedSlots: {customRender: 'action'},
    },
];

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

export default {
    name: 'BasicForm',
    i18n: require('./i18n'),
    data() {
        return {
            uploadIndex: null,
            appearanceList: [],
            machineList: [],
            engineList: [],
            otherList: [],
            currentUploadImageIndex: null,
            keyword: null,
            machineStatus: [],
            machineStatusTips: '请选择',
            current: 1,  // 当前页码
            pageSize: 5, // 每页数量
            total: 0,   // 一共的机器数量
            userID: null,  // 用户id
            expandedKeys: [],
            selectedKeys: [], // 左侧区域选中的值
            checkedKeys: [],
            addOrUpdate: true,
            previewImage: null,
            previewVisible: false,
            form: this.$form.createForm(this, {name: 'coordinated'}),
            machineTypes: [],   // 所有的机械类型森林
            machineTypesBeFilter: [],   // 过滤了不显示的机械类型，除了当前编辑的机械的类型
            data: [],
            columns,
            visible: false,
            value: 1,
            provinces: [],    // 当前角色绑定的区域森林结构
            baseUrl: window.server.SERVER_API
        }
    },
    computed: {
        desc() {
            return this.$t('pageDesc')
        }
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        this.refreshList();

        this.getMachineCategory();
        this.getMechanices(this.current, this.pageSize, null, null);
    },
    methods: {
        getMachineCategory() {
            request("/adminMechanics/getcategory", METHOD.GET).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.machineTypes = res.data.data;
                    // 初始的情况没过滤，当点击添加和编辑时在从 machineTypes中过滤
                    this.machineTypesBeFilter = res.data.data;
                } else {
                    this.$message.error(this.data.msg);
                }
            })
        },
        changeMachineMark(item, value) {
            console.log(value);
            console.log(item);
            item.mark = value ? 1 : 0;

            request("/mechanics/updateMechanics", METHOD.PUT, item).then(res => {
                if (res.data.code === 1) {
                    this.onShowSizeChange(this.current, this.pageSize);
                }
            });
        },
        // 点击选择了一个区域
        onSelect(selectedKeys, info) {
            console.log(selectedKeys);
            this.selectedKeys = selectedKeys;
            console.log('onSelect', info);
            this.onShowSizeChange(this.current = 1, this.pageSize)
        },
        getMechanices(page, pageSize, sel_level, sel_key) {

            request("/mechanics/getMechanics", METHOD.GET, {
                userid: this.userID,
                staue: this.machineStatus[0],
                page: page,
                pageSize: pageSize === null ? this.pageSize : this.pageSize = pageSize,
                sel_key: sel_key,
                sel_level: sel_level,
                input: this.keyword
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.data = res.data.data.records;
                    this.total = res.data.data.total;
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        findAreaByKey(area, key) {

            if (area.children != null && area.children.length > 0) {
                // 有子节点查询所有的子节点
                for (let i = 0; i < area.children.length; i++) {
                    let result = this.findAreaByKey(area.children[i], key);
                    if (result != null) {
                        // 找到了直接返回结果
                        return result;
                    }
                }
            }

            // 没有子节点 或者子节点查完了，检查本身节点
            if (area.key === key) {
                // 找到了直接返回结果
                return area;
            } else {
                // 告诉父节点没找到，继续找
                return null;
            }

        },
        onShowSizeChange(current, pageSize) {
            let area = null;
            // 查找当前选中的层级
            if (this.selectedKeys.length !== 0) {
                // 左侧区域选中了层级就查询这个层级的设备
                for (let i = 0; i < this.provinces.length; i++) {
                    area = this.findAreaByKey(this.provinces[i], this.selectedKeys[0]);
                    if (area != null) {
                        // 找到了就发送请求结束
                        this.getMechanices(current, pageSize, area.level, this.selectedKeys[0]);
                        break;
                    }
                }
            } else {
                // 左侧区域没选择就查询所有的设备
                this.getMechanices(current, pageSize, null, null);
            }
        },
        onChange(page, pageSize) {
            this.onShowSizeChange(page, pageSize);
        },
        refreshList() {
            request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
                if (result.data.code === 1) {
                    this.provinces = result.data.data;

                } else {
                    this.$message.error(result.data.msg);
                }
            })
        },
        addMachine() {
            // 清空图片
            this.appearanceList = [];
            this.machineList = [];
            this.engineList = [];
            this.otherList = [];
            // 清空表单
            this.form.resetFields();

            // 过滤所有的隐藏的机械类型
            this.machineTypesBeFilter = this.machineTypes;

            this.filterMachineCategory(this.machineTypesBeFilter, -1);

            this.addOrUpdate = true;
            this.visible = true;
        },
        /**
         * @param {[]} machineCategories 没有过滤前的机械类型森林
         * @param exceptId 等于这个id的机械类型不会被删除
         */
        filterMachineCategory(machineCategories, exceptId) {
            for (let i = 0; i < machineCategories.length; i++) {
                if (machineCategories[i].mark === false && machineCategories[i].id !== exceptId) {
                    // 被隐藏的机械类型就删除掉
                    this.$delete(machineCategories, i);
                    i--;
                } else if (machineCategories[i].children.length > 0) {
                    // 递归处理子节点
                    this.filterMachineCategory(machineCategories[i].children, exceptId)
                }
            }
        },
        handleMenuClick(e) {

            switch (e.key) {
                case "0":
                    this.machineStatusTips = '静止';
                    break;
                case "1":
                    this.machineStatusTips = '工作';
                    break;
                case "2":
                    this.machineStatusTips = '离线';
                    break;
                case "3":
                    this.machineStatusTips = '强拆';
                    break;
                case "4":
                    this.machineStatusTips = '请选择';

                    this.machineStatus[0] = undefined;
                    this.onShowSizeChange(this.current, this.pageSize);
                    return;
            }
            console.log('click', e);
            this.machineStatus[0] = e.key;
            this.onShowSizeChange(this.current, this.pageSize);
        },
        onSearch() {
            // 搜索机器
            console.log("搜索机器");
            this.onShowSizeChange(this.current, this.pageSize)
        },
        recover(item) {
            // 强拆恢复，将机器的状态由强拆改为静止
            item.status = 0;

            request("/mechanics/updateMechanics", METHOD.PUT, item).then(res => {
                if (res.data.code === 1) {
                    this.onShowSizeChange(this.current, this.pageSize);
                }
            });
        },
        edit(item) {

            // complete data
            // 时间戳转成字符串,每一行的数据只需要转换一次就可以了
            // 通过判断类型变化确定是不是第一次转换
            if (typeof item.check_end_time === typeof 1) {
                let timeString = moment(item.check_end_time * 1000).format("YYYY-MM-DD");
                this.$set(item, "check_end_time", moment(timeString, 'YYYY-MM-DD'));
                this.$set(item, "areas", [parseInt(item.area_one), parseInt(item.area_two), parseInt(item.area_three)])

                let route = [];
                let type_id = [];
                this.searchMachineTypeByValue(this.machineTypes, item.type_id, route);

                // 返回的是叶节点到根节点的顺序，需要反转一下
                route.reverse();
                // 只需要key,不需要节点的其他信息
                for (let routeElement of route) {
                    type_id.push(routeElement.id)
                }

                // 覆盖之前记录一下机械类型id
                this.$set(item, "real_type_id", item.type_id);
                this.$set(item, "type_id", type_id);
            }

            console.log(item);

            // set data
            // 没有改变item的内容，每次都要执行
            if (item.appearance !== null && item.appearance.trim().length !== 0) {
                this.$set(this.appearanceList, 0, {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: this.baseUrl + item.appearance,
                });

            } else {
                this.$delete(this.appearanceList, 0)
            }

            if (item.name_tag !== null && item.name_tag.trim().length !== 0) {
                this.$set(this.machineList, 0, {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: this.baseUrl + item.name_tag,
                });

            } else {
                this.$delete(this.machineList, 0)
            }


            if (item.engine !== null && item.engine.trim().length !== 0) {
                this.$set(this.engineList, 0, {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: this.baseUrl + item.engine,
                });

            } else {
                this.$delete(this.engineList, 0)
            }


            if (item.other !== null && item.other.trim().length !== 0) {
                this.$set(this.otherList, 0, {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: this.baseUrl + item.other,
                });

            } else {
                this.$delete(this.otherList, 0)
            }


            this.$nextTick(() => {
                // 下次 DOM 更新循环之后执行,将值写到表单
                this.form.setFieldsValue(item);
            })

            this.machineTypesBeFilter = this.machineTypes;
            this.filterMachineCategory(this.machineTypesBeFilter, item.real_type_id);

            // show data
            this.addOrUpdate = false;
            this.visible = true;
        },

        // 确认删除设备
        confirm(id) {

            request("/mechanics/deleteMenchanicsByid?id=" + id, METHOD.DELETE).then((res) => {
                if (res.data.code === 1) {
                    this.$message.success("删除成功");

                    this.onShowSizeChange(this.current, this.pageSize)
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        cancel(e) {
            console.log(e);
        },
        /**
         * @param {[]} node 机械类型的森林
         * @param {*} value 要查找节点的id值
         * @param {[]} route 记录从查找节点到根节点的路径
         */
        searchMachineTypeByValue(node, value, route) {
            for (let i = 0; i < node.length; i++) {
                if (node[i].id === value) {
                    // 当前节点就是需要的节点，返回结果
                    route.push(node[i]);
                    return node[i];
                } else if (node[i].children !== undefined && node[i].children !== null) {
                    let result = this.searchMachineTypeByValue(node[i].children, value, route);
                    // 当前节点的子节点中找到了结果，返回
                    if (result != null) {
                        // 当前节点是找到节点的祖宗节点，记录一下
                        route.push(node[i]);
                        return result;
                    }
                } else if (i + 1 === node.length) {
                    // 当前层级节点及其子节点都没有，返回null
                    return null;
                }

                // 当前节点及其子节点都没有，查询当前层级的下一个节点及其子节点
            }
        },
        // 编辑界面点击确认的方法
        handleOk: function () {

            this.form.validateFields((err, values) => {
                if (!err) {
                    console.log('Received values of form: ', values);

                    Vue.set(values, "check_end_time", moment(values.check_end_time).valueOf() / 1000);
                    Vue.set(values, "area_one", values.areas[0]);
                    Vue.set(values, "area_two", values.areas[1]);
                    Vue.set(values, "area_three", values.areas[2]);
                    Vue.set(values, "agent_id", this.userID);


                    if (this.addOrUpdate) {
                        // 新添加的设备的状态默认为强拆
                        Vue.set(values, "status", 3);
                    }

                    Vue.set(values, "type_id", parseInt(values.type_id[values.type_id.length - 1], 10));

                    // 需要记录的图片地址 = 没有图片 ?  记录为null :  数据库保存的图片路径不需要域（协议+ip+端口）相关的信息
                    values.appearance = this.appearanceList.length === 0 ? null : this.appearanceList[0].url.replace(this.baseUrl, '');
                    values.name_tag = this.machineList.length === 0 ? null : this.machineList[0].url.replace(this.baseUrl, '');
                    values.engine = this.engineList.length === 0 ? null : this.engineList[0].url.replace(this.baseUrl, '');
                    values.other = this.otherList.length === 0 ? null : this.otherList[0].url.replace(this.baseUrl, '');

                    let route = [];
                    let type_name = [];
                    this.searchMachineTypeByValue(this.machineTypes, values.type_id, route);

                    // 返回的是叶节点到根节点的顺序，需要反转一下
                    route.reverse();
                    // 只需要category_name,不需要节点的其他信息
                    for (let routeElement of route) {
                        type_name.push(routeElement.category_name);
                    }

                    Vue.set(values, "type_name", type_name.join("-"));


                    // 发起更新设备信息的请求
                    request("/mechanics" + (this.addOrUpdate ? "/saveMechanics" : "/updateMechanics"), this.addOrUpdate ? METHOD.POST : METHOD.PUT, values).then((res) => {
                        if (res.data.code === 1) {
                            // 添加成功之后可以关闭添加弹窗
                            this.visible = false;

                            this.onShowSizeChange(this.current, this.pageSize)

                            this.$message.success("操作成功")
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                }


            });
        },
        handleCancel() {
            console.log('Clicked cancel button');
            this.visible = false;
        },
        async handlePreview(file) {
            console.log("执行了预览方法")
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        handleApprenceChange(info) {
            if (info.file.status === 'removed') {
                this.appearanceList = info.fileList;
            }
            this.handleChange(info);
        },
        handleMachineChange(info) {
            if (info.file.status === 'removed') {
                this.machineList = info.fileList;
            }
            this.handleChange(info);
        },
        handleEngineChange(info) {
            if (info.file.status === 'removed') {
                this.engineList = info.fileList;
            }
            this.handleChange(info);
        },
        handleOtherChange(info) {
            if (info.file.status === 'removed') {
                this.otherList = info.fileList;
            }
            this.handleChange(info);
        },
        handleChange(info) {
            console.log(info.file.status);
            if (info.file.status === 'uploading') {
                // 处理图片的预览
                this.handlePreview(info.file);
                this.loading = true;
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                console.log(info);
                console.log(this.uploadIndex);
                switch (this.uploadIndex) {
                    case 0:
                        this.appearanceList = info.fileList;
                        break
                    case 1:
                        this.machineList = info.fileList;
                        break
                    case 2:
                        this.engineList = info.fileList;
                        break
                    case 3:
                        this.otherList = info.fileList;
                        break
                    default:
                        this.$message.error("错误的上传主键id:" + this.uploadIndex);
                }
            }
        },
        uploadImage(e, i) {
            const formData = new FormData();
            formData.append("lemonFile", e.file)
            request("/mechanics/fileupload", METHOD.POST, formData, {
                // 因为我们上传了图片,因此需要单独执行请求头的Content-Type
                headers: {
                    // 表示上传的是文件,而不是普通的表单数据
                    'Content-Type': 'multipart/form-data'
                }
            }).then(res => {
                console.log(res);
                if (res.data != null) {

                    // 图片上传主键切换到上传成功的状态
                    this.$message.success("上传图片成功")


                    // 文件地址 = 服务器地址 +  接口返回的图片地址
                    e.file.url = this.baseUrl + res.data;

                    // 记录上传后图片的url,用于显示
                    switch (i) {
                        case 0:
                            this.$set(this.appearanceList, 0, e.file)
                            break;
                        case 1:
                            this.$set(this.machineList, 0, e.file)
                            break;
                        case 2:
                            this.$set(this.engineList, 0, e.file)
                            break;
                        case 3:
                            this.$set(this.otherList, 0, e.file)
                            break;
                        default:
                            this.$message.error("错误的上传主键id:" + this.uploadIndex);
                    }
                    e.onSuccess(res.data, e);
                } else {
                    this.$message.error("上传图片失败")
                }
            })
        },
        uploadAppearanceImg(e) {
            console.log("自定义的上传接口" + this.currentUploadImageIndex);
            console.log(e);
            this.uploadIndex = 0;
            this.uploadImage(e, 0);
        },
        uploadMachineImg(e) {
            console.log("自定义的上传接口" + this.currentUploadImageIndex);
            console.log(e);
            this.uploadIndex = 1;
            this.uploadImage(e, 1);
        },
        uploadEngineImg(e) {
            console.log("自定义的上传接口" + this.currentUploadImageIndex);
            console.log(e);
            this.uploadIndex = 2;
            this.uploadImage(e, 2);
        },
        uploadOtherImg(e) {
            console.log("自定义的上传接口" + this.currentUploadImageIndex);
            console.log(e);
            this.uploadIndex = 3;
            this.uploadImage(e, 3);
        }
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 2px dashed black;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
}
</style>
